Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Networking → HttpURLConnection Class

Networking

HttpURLConnection Class

The `HttpURLConnection` class in Java provides a way to make HTTP requests (GET, POST, PUT, DELETE, etc.) directly, without needing a third-party library like Apache HttpClient. It's a fundamental part of Java's networking capabilities, built into the `java.net` package. While simpler than dedicated HTTP client libraries, it can be sufficient for many tasks, especially those not requiring advanced features like connection pooling or asynchronous operations.

HttpURLConnection Features and Methods:

Connection Establishment: You create a `HttpURLConnection` object by calling `openConnection()` on a `URL` object. This opens a connection to the specified URL. HTTP Method Setting: You set the HTTP method (GET, POST, PUT, DELETE, etc.) using `setRequestMethod()`. Headers: You can add HTTP headers using `setRequestProperty()`. Headers are crucial for things like specifying content type, authorization, caching behavior, etc. Request Body (for POST, PUT, etc.): For methods that send data to the server (like POST and PUT), you need to write the data to the connection's output stream using `getOutputStream()`. Response Handling: After sending the request, you read the response from the connection's input stream using `getInputStream()` (for successful responses) or `getErrorStream()` (for error responses). The response includes the response code (e.g., 200 OK, 404 Not Found) and the response body. Connection Management: Methods like `setConnectTimeout()` and `setReadTimeout()` allow you to set timeouts to prevent your application from hanging indefinitely.

Making a GET Request

This example fetches the content of a webpage:
GET Request import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpGetExample { public static void main(String[] args) { try { URL url = new URL("https://www.tutorialix.com"); // Replace with your URL HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // Set connection and read timeouts (optional, but recommended) connection.setConnectTimeout(5000); // 5 seconds connection.setReadTimeout(5000); // 5 seconds int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); System.out.println("Response:\ " + response.toString()); } else { System.err.println("HTTP error code: " + responseCode); } connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }

Making a POST Request

This example sends data to a server:
POST Request import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpPostExample { public static void main(String[] args) { try { URL url = new URL("https://tutorialix.com/api/submit"); // Replace with your URL HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); // Set content type String jsonData = "{\\"key1\\":\\"value1\\", \\"key2\\":\\"value2\\"}"; // Your JSON data connection.setDoOutput(true); // Indicate that you'll send data DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); writer.writeBytes(jsonData); writer.flush(); writer.close(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); // Process the response (read the input stream) // ... (add code to read and handle the response) ... inputStream.close(); } else { System.err.println("HTTP error code: " + responseCode); } connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }

Output


Important Considerations: Error Handling: Always include robust error handling (try-catch blocks) to manage potential `IOExceptions` and other exceptions. Response Codes: Check the response code to determine if the request was successful. Codes in the 200 range generally indicate success, while codes in the 400 and 500 ranges indicate client-side and server-side errors, respectively. Resource Management: Always close streams and disconnect the connection using `connection.disconnect()` to release resources. Security: For sensitive data, use HTTPS (secured connections) and consider appropriate security measures for authentication and authorization (e.g., using OAuth or API keys).

Tutorials